import { defineStore } from "pinia"
import { UserInfo } from "@/models/user"
import { getLocalUserInfo, setLocalUserInfo, getLocalUserToken, setLocalUserToken } from "@/utils";
import { messageApi } from "@/services"
import { toast } from "vue3-toastify"

const useAppStore  = defineStore('app', {
    // state
    state:() =>({
        userToken: "",
        userInfo: {} as UserInfo,
        loadingCount: 0,
        menuSelectedKeys: [] as string[],
        menuOpenKeys: [] as string[],
        unreadMessageCount: 0,
    }),

    // actions
    actions:{
        // 初始化数据
        initData(){
            this.getUserInfo();
            this.getMsgUnreadCount();
        },
        
        // 获取未读消息数量
        async getMsgUnreadCount() {
            try {
                const res = await messageApi.getUnreadCount()
                this.unreadMessageCount = res
            } catch(err) {
                toast.error('获取未读消息数量出现异常：'+ err);
            }
        },
        
        // 设置用户Token
        async setUserToken(token: string) {
            this.userToken = token;
            setLocalUserToken(token);
        },

        // 获取用户Token
        getUserToken() {
            if (!this.userToken) {
                this.userToken = getLocalUserToken();
            }
            return this.userToken;
        },
        
        // 设置用户信息
        async setUserInfo(userInfo: UserInfo) {
            this.userInfo = userInfo;
            setLocalUserInfo(userInfo);
        },

        // 获取用户信息
        getUserInfo() {
            if (!this.userInfo || !this.userInfo.username) {
                this.userInfo = getLocalUserInfo();
            }
            return this.userInfo;
        },

        startLoading() {
            this.loadingCount++
        },
        endLoading() {
            this.loadingCount = Math.max(0, this.loadingCount - 1)
        },

        getUnreadMessageCount() {
            return this.unreadMessageCount;
        },

        setUnreadMessageCount(count: number) {
            this.unreadMessageCount = count;
        },
    },
    getters:{
        isLoading: (state) => state.loadingCount > 0,
        isLogin: (state) => state.userInfo && state.userInfo.username,
    }
})

export default useAppStore